import requests
import json
from finance_c2c.local_settings import Config


class GetWebUser(object):
    def __init__(self, scope, config=None):
        """
        :param scope:  snsapi_userinfo snsapi_base
        """
        self.scope = scope
        self.result_dict = dict()
        if not config:
            self.appid = Config.appid
            self.secret = Config.appsecret
        else:
            self.appid = config.appid
            self.secret = config.appsecret

    def get_code(self, re_url):
        """
        第一步：用户同意授权，获取code
        """
        key = 'index'
        url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=' \
              'code&scope=%s&state=%s#wechat_redirect' % (self.appid, re_url, self.scope, key)
        return url

    def get_access_token(self, code):
        """
        第二步：通过code换取网页授权access_token
        """
        url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&redirect_uri&secret=%s&' \
              'code=%s&grant_type=authorization_code' % (self.appid, self.secret, code)
        response = requests.get(url, verify=False)
        res_content = response.content
        res_content = json.loads(res_content)
        self.result_dict = res_content

    def refresh_access_token(self):
        """
        第三步：刷新access_token（如果需要）
        """
        print(self.appid)

    def get_user_info(self):
        """
        第四步：拉取用户信息(需scope为 snsapi_userinfo)
        直接调用第四部就行 不需要调用第二步
        """
        # result_dict = self.get_access_token(code)
        url = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s' \
              % (self.result_dict["access_token"], self.result_dict['openid'])
        response = requests.get(url, verify=False)
        user_info = response.content
        user_info = json.loads(user_info)
        return user_info
